package edu.udel.mboch.towerdefense;

public class SinglePlayerGame extends Game
{
	private static final long serialVersionUID = -3411776171366421930L;
	private SinglePlayerTDState state;
	private int[] difficulty;
	
	public SinglePlayerGame(SinglePlayerTDState state)
	{
		super();
		this.state = state;
		difficulty = Levels.MEDIUM;
		actors.clear();
		addActor(state.getPlayer());
		addActor(new TimeActor());
	}
	
	public SinglePlayerGame(SinglePlayerTDState state, int[] difficulty)
	{
		super();
		this.state = state;
		this.difficulty = difficulty;
		actors.clear();
		addActor(state.getPlayer());
		addActor(new TimeActor());
	}
	
	public SinglePlayerTDState getState()
	{
		return state;
	}
	
	public boolean isEnd()
	{
		return state.getPlayer().getLives() <= 0 || (state.getWaves().getWaves().size() == 0 && state.getGrid().getMobs().size() == 0);
	}
	
	public Player getWinner()
	{
		if(state.getPlayer().getLives()>0)
			return state.getPlayer();
		return null;
	}
	
	public void update()
	{
		if(!isEnd())
			for(Actor a : actors)
			{
				TDMove move = a.getNextMove(state);
				if(move != null && move.isValid(state))
					move.make(state);
					if(move instanceof PlayerBuildMove)
						state.getPlayer().getTowers().add(((PlayerBuildMove)move).getTower());		
			}
	}
	
	public void restart()
	{
		Player player;
		if(state.getPlayer() instanceof SingleHumanPlayer)
			player = new SingleHumanPlayer(state.getPlayer().getName());
		else
			player = new SingleAIPlayer(state.getPlayer().getName());
		state = new SinglePlayerTDState(Levels.loadFromStringRandomSP(difficulty), player);
		actors.clear();
		addActor(player);
		addActor(new TimeActor());
		update();
	}
	
	public void startNewHumanGame(TDState state)
	{
		this.state = (SinglePlayerTDState)state;
		actors.clear();
		addActor(state.getPlayer());
		addActor(new TimeActor());
	}
}
